package com.comment.config.dao.typeHandler;

import com.comment.config.dao.type.Between;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.jetbrains.annotations.NotNull;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class SetBetweenHandler extends BaseTypeHandler<Set<Between>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<Between> parameter, JdbcType jdbcType) throws SQLException {
        String serialized = toStrBy(parameter);
        ps.setString(i, serialized);
    }

    @Override
    public Set<Between> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String serialized = rs.getString(columnName);
        return getBetweenSet(serialized);
    }

    @Override
    public Set<Between> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String serialized = rs.getString(columnIndex);
        return getBetweenSet(serialized);
    }

    @Override
    public Set<Between> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String serialized = cs.getString(columnIndex);
        return getBetweenSet(serialized);
    }

    private static @NotNull Set<Between> getBetweenSet(String serialized) {
        Set<Between> betweenSet = new HashSet<>();
        String[] split = serialized.split(",");
        for (String s : split) {
            String[] split1 = s.split("-");
            Between between = new Between();
            between.setStart(Integer.valueOf(split1[0]));
            between.setEnd(Integer.valueOf(split1[1]));
            betweenSet.add(between);
        }
        return betweenSet;
    }
    private String toStrBy(Set<Between> parameter) {
        StringBuilder sb = new StringBuilder();
        for (Between between : parameter) {
            sb.append(between.getStart()).append("-").append(between.getEnd()).append(",");
        }
        return sb.toString();
    }
}
